import {cloneElement, useRef, useEffect} from 'react';

import useResizeObserver from './useResizeObserver';

const Measurer = ({children, currentHeight, updateHeight, ...props}) => {

  const ref = useRef(null)

  const {height: resizedHeight} = useResizeObserver(ref.current);

  const handleResize = () => {

    updateHeight({
      currentHeight: resizedHeight ?? ref.current?.getBoundingClientRect().height,
      resized: resizedHeight !== undefined,
      previousHeight: currentHeight,
      ...props,
    })
  }

  useEffect(() => {
    handleResize();
  }, [currentHeight, resizedHeight]);
  
  return cloneElement(children, {ref})
}

export default Measurer;